package com.zhiwang.xiaoqu.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.zhiwang.xiaoqu.R
import dp

class TaskViewGroup : ViewGroup {

    var spanCount = 3

    var textSize = 16

    var textColor: Int = Color.BLACK

    var disableTextColor: Int = Color.GRAY

    @DrawableRes
    var unfinishedImageRes: Int = R.drawable.task_unfinished

    var fakeMock = false

    var itemMargin: Int = 10.dp

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.TaskViewGroup)

        spanCount = typedArray.getInt(R.styleable.TaskViewGroup_span_count, 3)

        textSize = typedArray.getDimensionPixelSize(R.styleable.TaskViewGroup_text_size, 16)

        itemMargin = typedArray.getDimensionPixelSize(R.styleable.TaskViewGroup_tasks_margin, 16)

        textColor = typedArray.getColor(
            R.styleable.TaskViewGroup_text_color,
            ContextCompat.getColor(context, R.color.colorPrimary)
        )

        disableTextColor = typedArray.getColor(
            R.styleable.TaskViewGroup_disable_text_color,
            ContextCompat.getColor(context, R.color.colorAccent)
        )

        fakeMock = typedArray.getBoolean(R.styleable.TaskViewGroup_fake_mock, false)
        typedArray.recycle()

        if (fakeMock) {
            setTasks(
                arrayListOf(
                    DailyTask("", false, "未完成"),
                    DailyTask("", false, "未完成"),
                    DailyTask("", false, "未完成"),
                    DailyTask("", false, "未完成"),
                    DailyTask("", false, "未完成")
                )
            )
        }
    }

    val TAG = "TaskViewGroup"
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        var height = 0
        var width = 0

        var tempH = 0
        var tempW = 0


        for (i in 0 until childCount) {

            val child = getChildAt(i)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)

            val layoutParams = child.layoutParams as LayoutParams

            tempW += child.measuredWidth + layoutParams.leftMargin + layoutParams.rightMargin

            if (tempH == 0)
                tempH = child.measuredHeight + layoutParams.bottomMargin + layoutParams.topMargin

            if (i % spanCount == 0) {
                height += tempH
                tempH = 0
            }

            if (i == childCount - 1 || i % spanCount == spanCount - 1) {
                width = Math.max(width, tempW)
                tempW = 0
            }

        }

        Log.i(TAG, "onMeasure: $height")

        setMeasuredDimension(width, height)

    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {


        var width = 0
        var height = 0

        var tempH = 0


        val anchorChild = getChildAt(0)

        val lp = anchorChild.layoutParams as LayoutParams

        val exactWidth = anchorChild.measuredWidth + lp.leftMargin + lp.rightMargin

        val exactHeight = anchorChild.measuredHeight + lp.topMargin + lp.bottomMargin

        for (i in 0 until childCount) {
            //换行
            if (i % spanCount == 0) {
                height += tempH
                tempH = 0
                width = 0

                val rows = childCount / spanCount + (if (childCount % spanCount == 0) 0 else 1)
                val currRow = i / spanCount
                val currRowItemCount =
                    if (currRow == rows - 1) childCount - spanCount *  (rows - 1) else spanCount

                width = (spanCount * exactWidth - currRowItemCount * exactWidth) / 2

                Log.i(TAG, "onLayout:$rows $currRow  $currRowItemCount")
            }

            val child = getChildAt(i)

            val layoutParams = child.layoutParams as LayoutParams

            val left = width + layoutParams.leftMargin
            val top = height + layoutParams.topMargin
            val right = left + child.measuredWidth
            val bottom = top + child.measuredHeight

            child.layout(left, top, right, bottom)

            if (tempH == 0)
                tempH = child.measuredHeight + layoutParams.topMargin + layoutParams.bottomMargin

            width += child.measuredWidth + layoutParams.leftMargin + layoutParams.rightMargin

        }

    }


    fun setTasks(tasks: List<DailyTask>) {

        removeAllViews()
        tasks.forEach {

            val linearLayoutParams = LayoutParams(-2, -2)
            linearLayoutParams.setMargins(itemMargin, itemMargin, itemMargin, itemMargin)

            val imageView = ImageView(context)
            val textView = TextView(context)

            val linearlayout = LinearLayout(context)
            linearlayout.orientation = LinearLayout.VERTICAL

            val ivLayoutParams = LinearLayout.LayoutParams(60.dp, 60.dp)

            val tvlayoutParams = LinearLayout.LayoutParams(-2, -2)
            tvlayoutParams.topMargin = 10.dp
            tvlayoutParams.gravity = Gravity.CENTER_HORIZONTAL

            linearlayout.addView(imageView, ivLayoutParams)


            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toFloat())
            textView.setTextColor(if (it.isDone) textColor else disableTextColor)
            textView.text = it.taskDesc
            linearlayout.addView(textView, tvlayoutParams)

            if (it.isDone)
                Glide.with(context)
                    .load(it.imageUrl)
                    .into(imageView)
            else imageView.setImageResource(unfinishedImageRes)

            addView(linearlayout, linearLayoutParams)
        }

    }


    override fun generateDefaultLayoutParams(): LayoutParams {
        return LayoutParams(-2, -2)
    }

    class LayoutParams : MarginLayoutParams {

        constructor(c: Context?, attrs: AttributeSet?) : super(c, attrs)
        constructor(width: Int, height: Int) : super(width, height)
    }


    class DailyTask(var imageUrl: String, var isDone: Boolean, var taskDesc: String)
}